#include "lc_op2_Operator.h"
#include <sys/stat.h>
#include <fcntl.h>

#define BUFFER_SIZE 8192


void 
op2::handleMyPort(NetRequest * data, unsigned long dataSize)
{
	assert(data != NULL);

        char *buffer = new char[BUFFER_SIZE];
	FILE *f;
	int rd;
	struct stat sb;
	int res,data_length;
	char file_name[128];
        
	char *root= "/home/riche";
	char *file= data->getBuffer();
	char *content="text/plain";

	sprintf(file_name, "%s/%s", root, file);
	res = stat(file_name, &sb);
	int file_size = sb.st_size;

	if (res < 0) {
		assert(data != NULL);
		char *msg1 = "HTTP/1.1 404 File not found\r\n";
		char msg[128];

		sprintf(msg, "Content-Length: %d\r\n", strlen(msg1));
		strcpy(buffer,msg);
		sprintf(msg, "Server: lagniappe \r\n");
		strcat(buffer,msg);
		sprintf(msg, "Content-Type: %s\r\n\r\n", content);
		strcat(buffer,msg);
		strcat(buffer,msg1);
	}
	else {
		int ix=0;
		char *ptr;
		int header_len;

		char hdrs[BUFFER_SIZE];
		if (0) {
			sprintf(hdrs, "HTTP/1.1 200 OK\r\nContent-type: %s\r\nServer: Lagniappe 0.1\r\nConnection: close\r\nContent-Length: %d\r\n\r\n",
					content, file_size);
		}
		else {
			sprintf(hdrs, "HTTP/1.1 200 OK\r\nContent-type: %s\r\nServer: Lagniappe 0.1\r\nContent-Length: %d\r\n\r\n",
					content, file_size);
		}
		header_len = strlen(hdrs);
                strcpy(buffer,hdrs);

		int fd = open(file_name, O_RDONLY);
		if (fd < 0) {
			perror("Reading");
			//closeSocket(in->socket);
			return ;
		}

		do{

			if ((rd = read(fd, hdrs, BUFFER_SIZE-header_len-ix)) < 0) {
				perror("read");
				//closeSocket(in->socket);
				return ;
			}
                        strcat(buffer+header_len+ix,hdrs);
                        
			ix += rd;
                        data_length = header_len+ix;
                        
		} while (ix < sb.st_size);
		close(fd);
	}
	NetRequest *out_data = new NetRequest(buffer,data->getSocketID(),strlen(buffer));
	assert(out_data != NULL);
	out(out_data, dataSize);
	free(data->getBuffer());
	delete data;
	return;
	
}

